package com.zhouhailin.shirospringbootdemo.controller;

import com.zhouhailin.shirospringbootdemo.entity.User;
import com.zhouhailin.shirospringbootdemo.service.UserService;
import com.zhouhailin.shirospringbootdemo.utils.JWTUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author zhouhailin
 * @date 2023/1/11 14:39
 */
@RestController
public class UserJWTController {
    private static final Logger logger = LoggerFactory.getLogger(UserJWTController.class);

    @Resource
    private UserService userService;

    @GetMapping("/user/jwt/login")
    public Map<String, Object> login(User user) {
        Map<String, Object> result = new HashMap<>();
        logger.info("用户名：[{}]", user.getUsername());
        logger.info("密码：[{}]", user.getPassword());

        // 登录
        try {
            User userLogin = userService.login(user);
            // 存放playload
            Map<String, String> map = new HashMap<>();
            map.put("id", userLogin.getId());
            map.put("username", userLogin.getUsername());
            String token = JWTUtils.getToken(map);
            result.put("state", true);
            result.put("msg", "登录成功！");
            // 登录成功返回token信息
            result.put("token", token);
        } catch (UnsupportedEncodingException e) {
            logger.error("登录失败！", e);
            result.put("state", false);
            result.put("msg", e.getMessage());
        }
        return result;
    }

}
